package data.platform.common.merge;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDateTime;

@Getter
@Setter
@NoArgsConstructor
public class CommonAggregateItem extends AggregateItem {

    private Double avg = 0.0;

    private Double max = Double.NEGATIVE_INFINITY;

    private Double min = Double.POSITIVE_INFINITY;

    private Double sum = 0.0;

    private Integer count = 0;

    private Double latestValue;

    private LocalDateTime latestEventTime;

    private LocalDateTime maxEventTime;

    private LocalDateTime minEventTime;

    public CommonAggregateItem(MergePeriod mergePeriod, MergeTimeWindow mergeTimeWindow) {
        super(mergePeriod, mergeTimeWindow);
    }

    public void compute(Double value, LocalDateTime eventTime) {
        latestValue = value;
        latestEventTime = eventTime;
        if (max.compareTo(value) < 0) {
            max = value;
            maxEventTime = eventTime;
        }
        if (min.compareTo(value) > 0) {
            min = value;
            minEventTime = eventTime;
        }
        sum += value;
        count++;
        avg = sum / count;
        dirty.compareAndSet(false, true);
    }

    @Override
    public String toString() {
        return "CommonAggregateItem{" +
                "avg=" + avg +
                ", max=" + max +
                ", min=" + min +
                ", sum=" + sum +
                ", count=" + count +
                ", latestValue=" + latestValue +
                ", latestEventTime=" + latestEventTime +
                ", maxEventTime=" + maxEventTime +
                ", minEventTime=" + minEventTime +
                ", dirty=" + dirty +
                '}';
    }
}
